const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;
const { User, groupChat } = require('../../../models');
const { BASE_URL } = require('../../../config');

// 获取群成员
async function getGroupMembers(io, socket, data, callback) {
    try {
        const group = await groupChat.findById(data.groupId)
            .populate('members', 'nickname headImgUrl phone');
        
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }
        
        // 格式化成员数据
        const members = group.members.map(member => {
            return {
                _id: member._id,
                nickname: member.nickname,
                headImgUrl: member.headImgUrl.startsWith('http') ? member.headImgUrl : BASE_URL + member.headImgUrl,
                phone: member.phone
            };
        });
        
        return callback({ 
            code: 200, 
            message: '获取群成员成功',
            members,
            owner: group.owner
        });
    } catch (error) {
        console.error('获取群成员失败:', error);
        return callback({ code: 500, message: '获取群成员失败: ' + error.message });
    }
}

// 更新群公告
async function updateGroupAnnouncement(io, socket, data, callback) {
    try {
        const { groupId, userId, announcement } = data;
        
        // 检查用户是否是群主
        const group = await groupChat.findById(groupId)
            .populate('owner', 'nickname');
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }
        
        if (group.owner._id.toString() !== userId) {
            return callback({ code: 403, message: '只有群主可以修改群公告' });
        }
        
        // 更新群公告及其相关信息
        group.announcement = announcement;
        group.announcementUpdateTime = new Date();
        group.announcementUpdater = userId;
        await group.save();
        
        // 获取群主信息，用于发送通知
        const updater = await User.findById(userId, 'nickname');
        
        // 通知所有群成员群公告已更新
        io.to(groupId.toString()).emit('groupAnnouncementUpdated', {
            groupId,
            announcement,
            updatedBy: userId,
            updaterName: updater ? updater.nickname : group.owner.nickname,
            updateTime: group.announcementUpdateTime
        });
        
        // 向群聊发送系统消息
        const systemMessage = {
            content: `群公告已更新，请查看`,
            type: 'system',
            timestamp: new Date(),
            sender: 'system',
            groupId: groupId
        };
        
        io.to(groupId.toString()).emit('groupSystemMessage', systemMessage);
        
        return callback({ 
            code: 200, 
            message: '更新群公告成功'
        });
    } catch (error) {
        console.error('更新群公告失败:', error);
        return callback({ code: 500, message: '更新群公告失败: ' + error.message });
    }
}

// 重命名群聊
async function renameGroup(io, socket, data, callback) {
    try {
        const { groupId, userId, newName } = data;
        
        // 检查用户是否是群主
        const group = await groupChat.findById(groupId);
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }
        
        if (group.owner.toString() !== userId) {
            return callback({ code: 403, message: '只有群主可以修改群名称' });
        }
        
        // 更新群名称
        group.groupName = newName;
        await group.save();
        
        // 通知所有群成员群名称已更新
        io.to(groupId.toString()).emit('groupRenamed', {
            groupId,
            newName,
            updatedBy: userId
        });
        
        return callback({ 
            code: 200, 
            message: '修改群名称成功'
        });
    } catch (error) {
        console.error('修改群名称失败:', error);
        return callback({ code: 500, message: '修改群名称失败: ' + error.message });
    }
}

// 退出群聊
async function quitGroup(io, socket, data, callback) {
    try {
        const { groupId, userId } = data;
        
        // 检查群聊是否存在
        const group = await groupChat.findById(groupId);
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }
        
        // 检查用户是否是群主
        const isOwner = group.owner.toString() === userId;
        if (isOwner) {
            return callback({ code: 403, message: '群主不能退出群聊，请先转让群主或解散群聊' });
        }
        
        // 从群成员中移除用户
        const memberIndex = group.members.findIndex(
            member => member.toString() === userId
        );
        
        if (memberIndex === -1) {
            return callback({ code: 404, message: '您不是该群成员' });
        }
        
        group.members.splice(memberIndex, 1);
        await group.save();
        
        // 从用户的加入群列表中移除该群
        const user = await User.findById(userId);
        if (user) {
            const groupIndex = user.joinedGroups.findIndex(
                joinedGroup => joinedGroup.toString() === groupId
            );
            
            if (groupIndex !== -1) {
                user.joinedGroups.splice(groupIndex, 1);
                await user.save();
            }
            
            // 让用户离开该群的socket房间
            if (socket) {
                socket.leave(groupId.toString());
            }
        }
        
        // 通知群内其他成员有人退出
        io.to(groupId.toString()).emit('memberQuitGroup', {
            groupId,
            userId,
            nickname: user ? user.nickname : '用户'
        });
        
        return callback({ 
            code: 200, 
            message: '退出群聊成功'
        });
    } catch (error) {
        console.error('退出群聊失败:', error);
        return callback({ code: 500, message: '退出群聊失败: ' + error.message });
    }
}

// 解散群聊
async function dismissGroup(io, socket, data, callback) {
    try {
        const { groupId, userId } = data;
        
        // 检查群聊是否存在
        const group = await groupChat.findById(groupId);
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }
        
        // 检查用户是否是群主
        if (group.owner.toString() !== userId) {
            return callback({ code: 403, message: '只有群主可以解散群聊' });
        }
        
        // 获取所有群成员
        const memberIds = [...group.members.map(id => id.toString())];
        
        // 通知所有群成员群聊已解散
        io.to(groupId.toString()).emit('groupDismissed', {
            groupId,
            groupName: group.groupName,
            dismissedBy: userId
        });
        
        // 从所有成员的joinedGroups中移除该群
        await User.updateMany(
            { _id: { $in: memberIds } },
            { $pull: { joinedGroups: new ObjectId(groupId) } }
        );
        
        // 解散群聊（从数据库中删除）
        await groupChat.findByIdAndDelete(groupId);
        
        return callback({ 
            code: 200, 
            message: '解散群聊成功'
        });
    } catch (error) {
        console.error('解散群聊失败:', error);
        return callback({ code: 500, message: '解散群聊失败: ' + error.message });
    }
}

// 邀请群成员
async function inviteGroupMembers(io, socket, data, callback) {
    try {
        const { groupId, inviterId, invitees } = data;
        
        // 检查群聊是否存在
        const group = await groupChat.findById(groupId).populate('members', '_id');
        if (!group) {
            return callback({ code: 404, message: '群聊不存在' });
        }
        
        // 检查邀请人是否是群成员
        const isMember = group.members.some(member => member._id.toString() === inviterId);
        if (!isMember) {
            return callback({ code: 403, message: '您不是该群成员，无法邀请他人' });
        }
        
        // 检查群成员数量是否超过上限
        if (group.members.length + invitees.length > (group.maxMembers || 500)) {
            return callback({ code: 400, message: '群成员数量已达上限' });
        }
        
        // 获取邀请人信息
        const inviter = await User.findById(inviterId, 'nickname phone');
        if (!inviter) {
            return callback({ code: 404, message: '邀请人不存在' });
        }
        
        // 为每个被邀请人创建群通知
        for (const inviteeId of invitees) {
            // 检查被邀请人是否已经是群成员
            const isAlreadyMember = group.members.some(member => member._id.toString() === inviteeId);
            if (isAlreadyMember) {
                continue;
            }
            
            // 创建群邀请
            socket.emit('create_group_invitation', {
                inviterPhone: inviter.phone,
                groupId,
                userId: inviteeId
            }, (response) => {
                console.log('创建群邀请结果:', response);
            });
        }
        
        return callback({ 
            code: 200, 
            message: '邀请发送成功'
        });
    } catch (error) {
        console.error('邀请群成员失败:', error);
        return callback({ code: 500, message: '邀请群成员失败: ' + error.message });
    }
}

module.exports = {
    getGroupMembers,
    updateGroupAnnouncement,
    renameGroup,
    quitGroup,
    dismissGroup,
    inviteGroupMembers
}   